/*
 * @Author       : wfl
 * @LastEditors  : wfl
 * @description  :
 * @updateInfo   :
 * @Date         : 2023-06-06 16:57:06
 * @LastEditTime : 2023-08-23 17:21:28
 */
import fs from 'fs'
import path from 'path'
import pkg from '../package.json'

const deleteDirectoryRecursive = (path: string) => {
  if (fs.existsSync(path)) {
    fs.readdirSync(path).forEach(file => {
      const curPath = `${path}/${file}`
      if (fs.lstatSync(curPath).isDirectory()) { // recurse
        deleteDirectoryRecursive(curPath)
      }
      else { // delete file
        fs.unlinkSync(curPath)
      }
    })
    fs.rmdirSync(path)
  }
}

const checkPck = (name: string) => {
  return (name in pkg.dependencies) || (name in pkg.devDependencies)
}
/**
 * 复制目录下的文件夹至指定位置
 * @param sourceDir 源目录路径
 * @param destDir 目标目录路径
 */
function copyDir(sourceDir: string, destDir: string, first = false) {
  if (first) {
    if (sourceDir.includes('iking-global-mainapp') && checkPck('iking-global-mainapp')) {
      deleteDirectoryRecursive('src/global')
      deleteDirectoryRecursive('src/MainApp')
    }
    if (sourceDir.includes('iking-assets-locales') && checkPck('iking-assets-locales')) {
      deleteDirectoryRecursive('src/assets')
      deleteDirectoryRecursive('src/locales')
    }

    const split = sourceDir.split('/')
    const pluginName = split.length > 2 ? split[1] : null
    const reDir = pluginName && pluginName.split('-')
    // 判断源目录是否存在
    if (!fs.existsSync(sourceDir)) {
      console.info(`\x1B[32m[IKING-ADMIN] \x1B[31m未使用插件${pluginName}. ${reDir?.[1]}和${reDir?.[2]}目录将不会被替换`)
      return
    }
    else {
      console.info(`\x1B[32m[IKING-ADMIN] \x1B[36m已加载插件${pluginName}. ${reDir?.[1]}和${reDir?.[2]}目录将会被替换`)
    }
  }
  // 判断目标目录是否存在，不存在则创建它
  if (!fs.existsSync(destDir))
    fs.mkdirSync(destDir)

  // 遍历源目录中的所有文件和子目录
  fs.readdirSync(sourceDir).forEach(file => {
    const sourcePath = path.join(sourceDir, file)
    const destPath = path.join(destDir, file)

    // 如果是子目录，则递归调用copyDir()函数进行复制
    if (fs.statSync(sourcePath).isDirectory()) {
      copyDir(sourcePath, destPath)
    }
    else {
      // 如果是文件，则直接复制到目标目录中
      fs.copyFileSync(sourcePath, destPath)
    }
  })
}

const copyMain = () => {
  copyDir('node_modules/iking-global-mainapp/pkg', 'src', true)
}

const copyAssets = () => {
  copyDir('node_modules/iking-assets-locales/pkg', 'src', true)
}

export {
  copyDir,
  copyMain,
  copyAssets
}
